package org.libarae.communication.response;

import java.io.ByteArrayOutputStream;
import java.util.Vector;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.libarae.communication.HTTPUtils;
import org.libarae.communication.XmlParseException;
import org.libarae.communication.common.Book;
import org.libarae.communication.common.Type;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;


public class BookSearchResponse extends Response{	
	Vector<Book> mResultBooks = new Vector<Book>();

	public BookSearchResponse(int status){
		super(Type.BOOK_SEARCH, status);
	}
	
	public BookSearchResponse(int status, Vector<Book> resultBooks){
		super(Type.BOOK_SEARCH, status);	
		setResultBooks(resultBooks);
	}

	@Override
	public String createXML() throws XmlParseException {
		Document doc;
		try{
			//setup the factory to build the xml
			DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
			doc = documentBuilder.newDocument();
		}
		catch (Exception e) {
			throw new XmlParseException("Error creating XML Builder",e);
		}
		
		//create the xml
		Element rootElement = doc.createElement("type");
		rootElement.setAttribute("typeID", super.getType()+"");
		doc.appendChild(rootElement);
		//user name
		Element node = doc.createElement("mStatus");
		node.setTextContent(getStatus()+"");
		rootElement.appendChild(node);
		
		//put vector in to the xml
		node = doc.createElement("mResultBooks");
		for(Book b : mResultBooks){
			Element subNode =  doc.createElement("Book");
			b.setPicture(null);
			b.createXml(doc, subNode);
			node.appendChild(subNode);
		}	
		rootElement.appendChild(node);
		
		//export the xml to a string
		String output = null;
		try {
			ByteArrayOutputStream byteArrayOutput = new ByteArrayOutputStream();
			TransformerFactory transformerFactory = TransformerFactory.newInstance();
			Transformer transformer = transformerFactory.newTransformer();
			DOMSource source = new DOMSource(doc);
			StreamResult result = new StreamResult(byteArrayOutput);
			transformer.transform(source, result);
			output = byteArrayOutput.toString();
		}
		catch (Exception e) {
			throw new XmlParseException("Error outputting XML to string", e);
		}
		
		//return the string
		return output;
	}

	@Override
	public void decodeXML(Document document) {
		// get the document root and node list
		Element root = document.getDocumentElement();
		NodeList nodeList = root.getChildNodes();

		// set all of the nodes in their proper places
		for (int i = 0; i < nodeList.getLength(); i++) {
			// find what node we have
			String nodeName = nodeList.item(i).getNodeName();
			if (nodeName.equals("mStatus")) {
				setStatus(Integer.parseInt(nodeList.item(i).getTextContent()));
			}
			else if (nodeName.equals("mResultBooks")) {
				NodeList nodeVector = nodeList.item(i).getChildNodes();
				mResultBooks = new Vector<Book>();
				for(int p = 0; p < nodeVector.getLength(); p++){
					Book book = new Book();
					book.decodeXML(nodeVector.item(p));					
					mResultBooks.add(book);
				}
			}
			else {
				System.err.println("Unknow field in object XML: " + nodeName);
			}
		}	
	}
	
	/**
	 * @return the mResultBooks
	 */
	public Vector<Book> getResultBooks() {
		return mResultBooks;
	}

	/**
	 * @param mResultBooks the mResultBooks to set
	 */
	public void setResultBooks(Vector<Book> mResultBooks) {
		if(mResultBooks == null)
			this.mResultBooks = new Vector<Book>();
		else
			this.mResultBooks = mResultBooks;
	}

	@Override
	public String createHTML() {
		//looks like:
		//Search:SearchedFor Test\n
		//Page:Page#
		String s = getHtmlHelperMessage();
		String searchedFor = s.substring(7, s.indexOf("\n"));
		int page = Integer.parseInt(s.substring(s.indexOf("Page:")+5));
		
		StringBuilder sb = new StringBuilder();
		sb.append("<div class=\"holder\">");
		sb.append("\n<head><script language=javascript  type='text/javascript'>var open = false; function switchDiv() {if(open == true){document.getElementById('advanceSearch').style.display = 'none'; open = false;}else {document.getElementById('advanceSearch').style.display = 'block'; open = true;}} </script></head>\n");
		
		//advance search button
		sb.append("<div class=\"advanceSearchButton\" onclick=\"switchDiv()\">");
		sb.append("Advance Search");
		sb.append("</div>");
		
		//for the search
		sb.append("<div id=\"advanceSearch\" class=\"advanceSearch\">");
		sb.append("<form><center><table>");
		sb.append("<tr><td>Title:</td><td><input type=\"text\" name=\"mTitle\" /></td></tr>");	
		sb.append("<tr><td>Author:</td><td><input type=\"text\" name=\"mAuthor\" /></td></tr>");	
		sb.append("<tr><td>Year:</td><td><input type=\"text\" name=\"mYear\" /></td></tr>");	
		sb.append("<tr><td>Pub.:</td><td><input type=\"text\" name=\"mPublisher\" /></td></tr>");	
		sb.append("<tr><td>ISBN:</td><td><input type=\"text\" name=\"mIsbn\" /></td></tr>");		
		sb.append("</table></center><input type=\"submit\" value=\"Submit\" /></form>");
		sb.append("</div>");	
		
		if(getResultBooks().isEmpty())
			return HTTPUtils.HTMLPageHeader(searchedFor) + sb.toString()+"<center><br/><br/><strong>No Books Found</strong></div></center></div></body>";
		
		for( Book b : getResultBooks())
		{//Create a new row for each book result
			sb.append("\n<div class=\"bookHolder\"  onclick=\"location.href='/bookInfo.html?mBid=" + HTTPUtils.encodeURL("" + b.getBID()) + "';\">");
			String title = b.getTitle();
			if(title.length() > 20)
				title = title.substring(0,20)+"..";
			sb.append("<i>").append(title).append("</i>"); 
			String author = b.getAuthor();
			if(author.length() > 13)
				author = author.substring(0,13)+"..";
			sb.append(", by <b>").append(author).append("</b>");
			if(b.getISBN() != null && b.getISBN().length() > 0)
				sb.append("<br/>ISBN: ").append(b.getISBN());
			sb.append("<div style=\"float:right;\"><a class=\"nounderline\" href=\"/bookInfo.html?mBid=" + HTTPUtils.encodeURL("" + b.getBID()) +  "\" > Details </a></div>");
			sb.append("</div>");
		}
			

		
		//if we are on a middle page
		if(page != 0){
			sb.append("<a class=\"nounderline\" href=\"search.html?mOmniSearch=" + HTTPUtils.encodeURL(searchedFor) + "&mSearchPageNumber=" + (page-1) + "\">");
			sb.append("<div style=\"float:left;font-size:17px;padding:15px;\">&lt; Previous Page</div>").append("</a>");
		}
		
		sb.append("<a class=\"nounderline\" href=\"search.html?mOmniSearch=" + HTTPUtils.encodeURL(searchedFor) + "&mSearchPageNumber=" + (page+1) + "\">");
		sb.append("<div style=\"float:right;font-size:17px;padding:15px;\">Next Page &gt;</div>").append("</a>");
		sb.append("</div></body>");

		return HTTPUtils.HTMLPageHeader(searchedFor) +	sb.toString();
	}

}
